<template>
    <view>
      <!-- 第一行：仓库选择 + 库位扫码框 -->
      <view class="first-row">
        <!-- 仓库选择器 -->
        <picker mode="selector"
                :range="warehouseList"
                :value="selectedWarehouseIndex"
                @change="onWarehouseChange">
          <view class="picker">
            {{ warehouseDisplayText }}
          </view>
        </picker>
        
        <!-- 扫码输入框 -->
        <view class="scan-section">
          <view class="input-wrapper">
            <input 
              class="query-input" 
              v-model="scanInputValue"
              placeholder="扫描库位编码"
              @confirm="handleInputConfirm"
            />
            <view class="input-icon scan-icon">
              <uni-icons type="scan" size="16" color="#007AFF"></uni-icons>
            </view>
            <view class="input-icon clear-icon" @click="clearScanInput">
              <uni-icons type="clear" size="16" color="#999"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 提示信息 -->
      <view class="scan-tip" v-if="scanTip">
        {{ scanTip }}
      </view>
      
      <!-- 第二行：库区/库位选择 -->
      <view class="second-row">
        <picker mode="multiSelector"
                :range="columns"
                :value="indexes"
                @columnchange="onColumnChange"
                @change="onChange"
                @cancel="onCancel">
          <view class="picker">
            {{ locationDisplayText || '请选择库区/库位' }}
          </view>
        </picker>
      </view>
    </view>
  </template>
  
  <script>
  import { getTreeList } from '@/api/wm/warehouse.js'
  
  export default {
    name: 'warehouse',
    props: {
      // 分别控制三个层级的显示模式
      warehouseDisplayMode: {
        type: String,
        default: 'name' // 'name', 'code', 'both'
      },
      locationDisplayMode: {
        type: String,
        default: 'name' // 'name', 'code', 'both'
      },
      areaDisplayMode: {
        type: String,
        default: 'name' // 'name', 'code', 'both'
      },
      // 默认选择的数据，用于编辑时设置默认值
      defaultSelection: {
        type: Object,
        default: null
      }
    },
    data() {
      return {
        rawTree: [],
        warehouseList: [], // 仓库列表（包含占位符）
        selectedWarehouseIndex: 0, // 当前选中的仓库索引
        warehouseDisplayText: '请选择仓库', // 仓库显示文本
        columns: [[], []], // 二级联动：库区 + 库位
        indexes: [0, 0], // 初始化为选择第一个
        locationDisplayText: '', // 库区库位显示文本
        isPickerOpen: false, // 标记选择器是否打开
        lastConfirmedIndexes: [0, 0], // 记录最后确认的选择
        scanTip: '', // 扫码提示信息
        isScanning: false, // 扫码状态
        scanInputValue: '', // 扫码输入框的值
        selectedWarehouse: null, // 当前选中的仓库
        isEmptySelection: true, // 标记是否为空选择状态
        // PDA扫码防抖
        scanDebounceTimer: null // 扫码防抖定时器
      }
    },
    watch: {
      // 监听默认选择数据变化
      defaultSelection: {
        handler(newSelection) {
          if (newSelection && this.rawTree.length > 0) {
            this.setDefaultSelection(newSelection)
          }
        },
        immediate: true
      },
      
      // 监听扫码输入值变化，使用防抖处理PDA扫码
      scanInputValue: {
        handler(newValue, oldValue) {
          // 如果输入值发生变化且不为空
          if (newValue && newValue !== oldValue) {
            // 清除之前的防抖定时器
            if (this.scanDebounceTimer) {
              clearTimeout(this.scanDebounceTimer)
            }
            
            // 设置防抖定时器，300ms后执行扫码处理
            this.scanDebounceTimer = setTimeout(() => {
              console.log('PDA扫码防抖完成，处理扫码:', newValue.trim())
              this.handleScannedCode(newValue.trim())
            }, 300)
          }
        }
      }
    },
    async mounted() {
      await this.loadTreeData()
    },
    beforeDestroy() {
      // 清理防抖定时器
      if (this.scanDebounceTimer) {
        clearTimeout(this.scanDebounceTimer)
        this.scanDebounceTimer = null
      }
    },
    methods: {
      async loadTreeData() {
        try {
          const res = await getTreeList()
          
          if (res.code === 200 && res.data && res.data.length > 0) {
            // 过滤掉虚拟线边仓库
            const filteredData = res.data.filter(warehouse => warehouse.warehouseCode !== 'XBK_VIRTUAL')
            
            if (filteredData.length === 0) {
              uni.showToast({
                title: '暂无可用仓库',
                icon: 'none'
              });
              return
            }
            
            this.rawTree = filteredData.map((warehouse) => {
              const processedWarehouse = {
                id: warehouse.warehouseId,
                code: warehouse.warehouseCode,
                name: warehouse.warehouseName,
                children: (warehouse.children || []).map((location) => {
                  return {
                    id: location.locationId,
                    code: location.locationCode,
                    name: location.locationName,
                    children: (location.children || []).map((area) => {
                      return {
                        id: area.areaId,
                        code: area.areaCode,
                        name: area.areaName
                      }
                    })
                  }
                })
              }
              return processedWarehouse
            })
            
            this.initColumns()
            
            // 如果有默认选择数据，设置默认值
            if (this.defaultSelection) {
              this.setDefaultSelection(this.defaultSelection)
            }
          } else {
            uni.showToast({
              title: res.msg || '获取仓库数据失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('加载仓库数据失败:', error)
          uni.showToast({
            title: '加载仓库数据失败',
            icon: 'none'
          });
        }
      },
      
      initColumns() {
        if (this.rawTree.length === 0) {
          this.warehouseList = ['暂无数据']
          this.columns = [['暂无数据'], ['暂无数据']];
          this.warehouseDisplayText = '暂无数据'
          return;
        }
        
        // 初始化仓库列表（添加占位符）
        this.warehouseList = ['请选择仓库', ...this.rawTree.map(w => w.name)]
        
        // 默认选择占位符（索引0）
        this.selectedWarehouse = null
        this.selectedWarehouseIndex = 0
        this.warehouseDisplayText = '请选择仓库'
        this.updateColumns()
        this.indexes = [0, 0]
        this.lastConfirmedIndexes = [0, 0]
        this.isEmptySelection = true
      },
      
      // 更新列数据
      updateColumns() {
        if (!this.selectedWarehouse) {
          this.columns = [['请先选择仓库'], ['请先选择仓库']]
          return
        }
        
        // 第一列：当前选中仓库的库区列表，添加空选择占位符
        const locations = (this.selectedWarehouse.children || [])
          .map(l => this.getDisplayText(l, 'location'))
          .filter(text => text !== null) // 过滤掉null值
        this.columns[0] = ['请选择库区', ...locations]
        
        // 第二列：当前选中库区的库位列表
        if (this.indexes[0] > 0 && this.indexes[0] - 1 < (this.selectedWarehouse.children || []).length) {
          const l = this.selectedWarehouse.children[this.indexes[0] - 1]
          const areas = (l.children || [])
            .map(a => this.getDisplayText(a, 'area'))
            .filter(text => text !== null) // 过滤掉null值
          this.columns[1] = ['请选择库位', ...areas]
        } else {
          this.columns[1] = ['请先选择库区']
        }
      },
      
      // 获取显示文本 - 根据层级使用不同的显示模式
      getDisplayText(item, type) {
        if (!item) {
          // 不应该返回默认文本，因为空数据不应该作为选项
          return null
        }
        
        let displayMode = 'name'
        switch (type) {
          case 'warehouse':
            displayMode = this.warehouseDisplayMode
            break
          case 'location':
            displayMode = this.locationDisplayMode
            break
          case 'area':
            displayMode = this.areaDisplayMode
            break
        }
        
        let result = ''
        switch (displayMode) {
          case 'code':
            result = item.code || item.name
            break
          case 'both':
            result = `${item.name || ''}(${item.code || ''})`
            break
          case 'name':
          default:
            result = item.name
            break
        }
        
        // 如果结果为空，返回null而不是"未知"
        return result || null
      },
      
      onColumnChange(e) {
        const { column, value } = e.detail
        this.indexes[column] = value
        
        if (column === 0) {
          // 库区改变，重置库位选择为空选择状态
          this.indexes[1] = 0
          this.isEmptySelection = value === 0
        } else if (column === 1) {
          // 库位改变，更新空选择状态
          this.isEmptySelection = this.indexes[0] === 0 || value === 0
        }
        
        this.updateColumns()
        this.updateLocationDisplayText()
        
        // 关键修复：在滚动选择时也发送选中事件
        // 这样用户在选择过程中就能看到实时的选中结果
        this.emitSelected()
      },
      
      onChange(e) {
        // 用户确认选择
        this.indexes = e.detail.value
        this.lastConfirmedIndexes = [...this.indexes] // 保存确认的选择
        
        // 更新空选择状态
        this.isEmptySelection = this.indexes[0] === 0
        
        this.updateLocationDisplayText()
        this.emitSelected()
        this.isPickerOpen = false
      },
      
      onCancel() {
        // 用户取消选择，恢复到上次确认的选择
        this.indexes = [...this.lastConfirmedIndexes]
        this.updateColumns()
        this.updateLocationDisplayText()
        this.emitSelected() // 发送恢复后的选择
        this.isPickerOpen = false
      },
      
      // 更新库区/库位显示文本
      updateLocationDisplayText() {
        if (!this.selectedWarehouse) {
          this.locationDisplayText = '请先选择仓库'
          return
        }
        
        // 检查是否为空选择状态
        if (this.isEmptySelection || this.indexes[0] === 0) {
          this.locationDisplayText = '请选择库区/库位'
          return
        }
        
        const l = (this.selectedWarehouse?.children || [])[this.indexes[0] - 1]
        const a = (l?.children || [])[this.indexes[1] - 1]
        
        // 检查是否选择了占位符选项
        let locationText = ''
        if (this.indexes[0] > 0 && l) {
          locationText = this.getDisplayText(l, 'location')
        }
        
        let areaText = ''
        if (this.indexes[1] > 0 && a) {
          areaText = this.getDisplayText(a, 'area')
        }
        
        this.locationDisplayText = [locationText, areaText].filter(Boolean).join(' / ')
      },
      
      // 发送选中事件
      emitSelected() {
        if (!this.selectedWarehouse) {
          this.$emit('selected', {
            warehouse: null,
            location: null,
            area: null,
            warehouseId: null,
            warehouseCode: null,
            warehouseName: null,
            locationId: null,
            locationCode: null,
            locationName: null,
            areaId: null,
            areaCode: null,
            areaName: null
          })
          return
        }
        
        // 检查是否为空选择状态
        if (this.isEmptySelection || this.indexes[0] === 0) {
          this.$emit('selected', {
            warehouse: this.selectedWarehouse,
            location: null,
            area: null,
            warehouseId: this.selectedWarehouse?.id,
            warehouseCode: this.selectedWarehouse?.code,
            warehouseName: this.selectedWarehouse?.name,
            locationId: null,
            locationCode: null,
            locationName: null,
            areaId: null,
            areaCode: null,
            areaName: null
          })
          return
        }
        
        const l = (this.selectedWarehouse?.children || [])[this.indexes[0] - 1]
        const a = (l?.children || [])[this.indexes[1] - 1]
        
        // 向父组件传递选中的完整数据
        this.$emit('selected', {
          warehouse: this.selectedWarehouse,
          location: l,
          area: a,
          warehouseId: this.selectedWarehouse?.id,
          warehouseCode: this.selectedWarehouse?.code,
          warehouseName: this.selectedWarehouse?.name,
          locationId: l?.id,
          locationCode: l?.code,
          locationName: l?.name,
          areaId: a?.id,
          areaCode: a?.code,
          areaName: a?.name
        })
      },
      
      // 设置默认选择（用于编辑时）
      setDefaultSelection(selectionData) {
        if (!selectionData || !selectionData.warehouseId) {
          return
        }
        
        // 根据传入的数据查找对应的索引
        let warehouseIndex = -1
        let locationIndex = -1
        let areaIndex = -1
        
        // 查找仓库索引
        for (let i = 0; i < this.rawTree.length; i++) {
          if (this.rawTree[i].id == selectionData.warehouseId) {
            warehouseIndex = i
            break
          }
        }
        
        if (warehouseIndex >= 0) {
          const warehouse = this.rawTree[warehouseIndex]
          
          // 设置仓库选择（考虑占位符偏移）
          this.selectedWarehouseIndex = warehouseIndex + 1 // +1 因为有占位符
          this.selectedWarehouse = warehouse
          this.warehouseDisplayText = warehouse.name
          
          // 查找库区索引
          if (selectionData.locationId && warehouse.children && warehouse.children.length > 0) {
            for (let i = 0; i < warehouse.children.length; i++) {
              if (warehouse.children[i].id == selectionData.locationId) {
                locationIndex = i
                break
              }
            }
          }
          
          // 查找库位索引
          if (locationIndex >= 0 && selectionData.areaId && warehouse.children[locationIndex].children && warehouse.children[locationIndex].children.length > 0) {
            for (let i = 0; i < warehouse.children[locationIndex].children.length; i++) {
              if (warehouse.children[locationIndex].children[i].id == selectionData.areaId) {
                areaIndex = i
                break
              }
            }
          }
          
          // 设置索引（考虑占位符偏移）
          this.indexes = [locationIndex + 1, areaIndex + 1] // +1 因为有占位符
          this.lastConfirmedIndexes = [locationIndex + 1, areaIndex + 1]
          this.isEmptySelection = false
          
          // 更新显示
          this.updateColumns()
          this.updateLocationDisplayText()
          this.emitSelected()
        }
      },
      
      // 处理输入框确认（手动确认，立即处理）
      handleInputConfirm() {
        // 清除防抖定时器，立即处理
        if (this.scanDebounceTimer) {
          clearTimeout(this.scanDebounceTimer)
          this.scanDebounceTimer = null
        }
        
        if (this.scanInputValue.trim()) {
          console.log('手动确认扫码:', this.scanInputValue.trim())
          this.handleScannedCode(this.scanInputValue.trim())
        }
      },
    
      // 清空扫码输入框
      clearScanInput() {
        this.scanInputValue = ''
        this.scanTip = ''
        
        // 清除防抖定时器
        if (this.scanDebounceTimer) {
          clearTimeout(this.scanDebounceTimer)
          this.scanDebounceTimer = null
        }
      },
      
      // 仓库选择变化
      onWarehouseChange(e) {
        const warehouseIndex = e.detail.value
        this.selectedWarehouseIndex = warehouseIndex
        
        if (warehouseIndex === 0) {
          // 选择了占位符
          this.selectedWarehouse = null
          this.warehouseDisplayText = '请选择仓库'
        } else {
          // 选择了实际仓库（考虑占位符偏移）
          this.selectedWarehouse = this.rawTree[warehouseIndex - 1]
          this.warehouseDisplayText = this.selectedWarehouse.name
        }
        
        // 重置库区库位选择为空选择状态
        this.indexes = [0, 0]
        this.lastConfirmedIndexes = [0, 0]
        this.isEmptySelection = true
        
        // 更新列数据和显示
        this.updateColumns()
        this.updateLocationDisplayText()
        this.emitSelected()
      },
      
      // 处理扫码结果
      handleScannedCode(scannedCode) {
        console.log('开始处理扫码:', scannedCode)
        
        if (!scannedCode || !this.rawTree.length) {
          console.log('扫码数据无效或树数据为空')
          // 清空扫码框
          this.scanInputValue = ''
          return
        }
        
        // 检查是否已经选择了仓库
        if (!this.selectedWarehouse) {
          console.log('未选择仓库')
          this.scanTip = '请先选择仓库'
          setTimeout(() => {
            this.scanTip = ''
          }, 1500)
          // 清空扫码框
          this.scanInputValue = ''
          return
        }
        
        console.log('当前选中仓库:', this.selectedWarehouse.name, this.selectedWarehouse.code)
        console.log('仓库下的库区数量:', this.selectedWarehouse.children?.length || 0)
        
        // 在当前选中的仓库中查找库位
        let foundInCurrentWarehouse = false
        let targetLocationIndex = -1
        let targetAreaIndex = -1
        let matchType = ''
        
        // 先打印所有库区库位信息用于调试
        for (let lIndex = 0; lIndex < (this.selectedWarehouse.children || []).length; lIndex++) {
          const location = this.selectedWarehouse.children[lIndex]
          console.log(`库区${lIndex}:`, location.name, location.code)
          for (let aIndex = 0; aIndex < (location.children || []).length; aIndex++) {
            const area = location.children[aIndex]
            console.log(`  库位${aIndex}:`, area.name, area.code)
            
            // 1. 精确匹配
            if (area.code === scannedCode) {
              console.log('精确匹配找到库位!', area.code, '===', scannedCode)
              foundInCurrentWarehouse = true
              targetLocationIndex = lIndex
              targetAreaIndex = aIndex
              matchType = 'exact'
              break
            }
            // 2. 前缀匹配（处理PDA扫码不完整的情况）
            else if (area.code.startsWith(scannedCode) && scannedCode.length >= 3) {
              console.log('前缀匹配找到库位!', area.code, 'startsWith', scannedCode)
              foundInCurrentWarehouse = true
              targetLocationIndex = lIndex
              targetAreaIndex = aIndex
              matchType = 'prefix'
              break
            }
          }
          if (foundInCurrentWarehouse) break
        }
        
        if (foundInCurrentWarehouse) {
          console.log('扫码成功，更新选择:', targetLocationIndex, targetAreaIndex)
          // 在当前仓库中找到库位，更新选择（考虑占位符索引）
          this.indexes = [targetLocationIndex + 1, targetAreaIndex + 1]
          this.lastConfirmedIndexes = [targetLocationIndex + 1, targetAreaIndex + 1]
          this.isEmptySelection = false
          this.updateColumns()
          this.updateLocationDisplayText()
          this.emitSelected()
          
          // 显示成功提示
          const matchText = matchType === 'exact' ? '精确匹配' : '前缀匹配'
          this.scanTip = `扫码成功 (${matchText}): ${scannedCode}`
          setTimeout(() => {
            this.scanTip = ''
          }, 1500)
        } else {
          console.log('在当前仓库中未找到库位:', scannedCode)
          // 在当前仓库中未找到库位
          this.scanTip = `当前仓库下未找到库位: ${scannedCode}`
          setTimeout(() => {
            this.scanTip = ''
          }, 1500)
        }
        
        // 无论查找成功与否都清空扫码框
        this.scanInputValue = ''
      }
    }
  }
  </script>
  
  <style scoped>
  .first-row {
    display: flex;
    align-items: center;
    gap: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .scan-section {
    flex: 1;
  }
  
  .scan-section .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
  }
  
  .scan-section .input-wrapper .query-input {
    flex: 1;
    height: 80rpx;
    padding: 0 100rpx 0 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
    background: #fff;
    box-sizing: border-box;
    transition: all 0.3s ease;
  }
  
  .scan-section .input-wrapper .query-input:focus {
    border-color: #007AFF;
    box-shadow: 0 0 0 4rpx rgba(0, 122, 255, 0.1);
  }
  
  .scan-section .input-wrapper .query-input::placeholder {
    color: #999;
    font-size: 26rpx;
  }
  
  .scan-section .input-wrapper .input-icon {
    position: absolute;
    padding: 10rpx;
    border-radius: 50%;
    transition: all 0.3s ease;
  }
  
  .scan-section .input-wrapper .input-icon.scan-icon {
    right: 60rpx;
    background: rgba(0,122,255,0.08);
  }
  
  .scan-section .input-wrapper .input-icon.clear-icon {
    right: 16rpx;
  }
  
  .scan-section .input-wrapper .input-icon:active {
    background: rgba(0,0,0,0.05);
    transform: scale(0.9);
  }
  
  .second-row {
    margin-bottom: 20rpx;
  }
  
  .picker {
    padding: 20rpx;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    background-color: #fff;
    text-align: center;
  }
  
  .scan-tip {
    margin-top: 10rpx;
    padding: 10rpx;
    background-color: #f0f0f0;
    border-radius: 4rpx;
    font-size: 24rpx;
    color: #666;
    text-align: center;
  }
  </style>